from windoh.control import Control
from windoh.controls.label import Label
import pyglet
from pyglet.text.layout import IncrementalTextLayout, TextLayoutForegroundGroup, TextLayoutForegroundDecorationGroup, TextLayoutGroup
from pyglet import graphics 


class InputGroup(TextLayoutGroup):
    _scissor_x = 0
    _scissor_y = 0
    _scissor_width = 0
    _scissor_height = 0
    view_x = 0
    view_y = 0
    translate_x = 0 # x - view_x
    translate_y = 0 # y - view_y


class TextLayout(IncrementalTextLayout):
    def _init_groups(self, group):
        # Scrollable layout never shares group becauase of translation.   
        self.top_group = InputGroup(group)
        self.background_group = graphics.OrderedGroup(0, self.top_group)
        self.foreground_group = TextLayoutForegroundGroup(1, self.top_group)
        self.foreground_decoration_group = \
            TextLayoutForegroundDecorationGroup(2, self.top_group)


class TextInput(Control):
    
    class TextInputCaret(Control):
        pass

    def __init__(self, text=None, **kwargs):
        Control.__init__(self, **kwargs)
        self._text = text
        #self.label = Label(text, left=1, right=1, top=1, bottom=1, cursor='text')
        #self.append(self.label)
        #self.col = 0

        self.document = pyglet.text.document.UnformattedDocument(text)
        self.document.set_style(0, len(self.document.text),
            dict(color=(0, 0, 0, 255))
        )
        #font = self.document.get_font()
        #height = font.ascent - font.descent

        self.layout = TextLayout(
            self.document, 100, 100, multiline=False)
        self.layout.valign = 'bottom'
        self.caret = pyglet.text.caret.Caret(self.layout)

    def on_mouse_release(self, x, y, m, b):
        self.focus()

    #def on_text(self, text):
    #    l = self.label.label
    #    self.label.label = l[:self.col]+text+l[self.col:]

    def on_focus(self):
        print "on_focus"
        self.caret.visible = True
        self.caret.mark = 0
        self.caret.position = len(self.document.text)

    def on_blur(self):
        print "on_blur"
        self.caret.visible = False

    def on_text(self, text):
        print "on_text", text
        self.caret.on_text(text)
            
        





